<template>
  <div class="app-container">
    <a-form :model="queryParams" ref="queryRef" layout="inline" v-show="showSearch">
      <a-form-item label="赛段名称" name="sectionName">
        <a-input
          v-model:value="queryParams.sectionName"
          placeholder="请输入赛段名称"
          allow-clear
          @pressEnter="handleQuery"
        />
      </a-form-item>
      <a-form-item label="赛事名称" name="saishi">
        <a-select
          v-model:value="queryParams.saishi"
          placeholder="请选择赛事名称"
          allow-clear
          style="width: 100px"
          @pressEnter="handleQuery"
        >
          <a-select-option
            v-for="item in raceOptions"
            :key="item.value"
            :value="item.value"
          >
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="状态" name="status">
        <a-select v-model:value="queryParams.status" placeholder="请选择状态" allow-clear style="width: 100px">
          <a-select-option
            v-for="dict in race_status"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="handleQuery">
          <template #icon><SearchOutlined /></template>
          搜索
        </a-button>
        <a-button @click="resetQuery" style="margin-left: 8px">
          <template #icon><ReloadOutlined /></template>
          重置
        </a-button>
      </a-form-item>
    </a-form>

    <a-row :gutter="10" class="mb8">
      <a-col :span="1.5">
        <a-button
          type="primary"
          @click="handleAdd"
          v-privilege="['RaceSys:raceInfo:add']"
        >
          <template #icon><PlusOutlined /></template>
          新增
        </a-button>
      </a-col>
      <a-col :span="1.5">
        <a-button
          type="default"
          :disabled="single"
          @click="handleUpdate"
          v-privilege="['RaceSys:raceInfo:edit']"
        >
          <template #icon><EditOutlined /></template>
          修改
        </a-button>
      </a-col>
      <a-col :span="1.5">
        <a-button
          type="primary"
          danger
          :disabled="multiple"
          @click="handleDelete"
          v-privilege="['RaceSys:raceInfo:remove']"
        >
          <template #icon><DeleteOutlined /></template>
          删除
        </a-button>
      </a-col>
      <a-col :span="1.5">
        <a-button
          type="default"
          @click="handleExport"
          v-privilege="['RaceSys:raceInfo:export']"
        >
          <template #icon><DownloadOutlined /></template>
          导出
        </a-button>
      </a-col>
<!--      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>-->
    </a-row>

    <a-table 
      :loading="loading" 
      :data-source="raceInfoList" 
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: handleSelectionChange }"
      :pagination="false"
      row-key="sectionName"
    >
      <a-table-column title="赛段名称" data-index="sectionName" align="center" />
      <a-table-column title="赛事名称" data-index="saishi" align="center" />
      <a-table-column title="赛段介绍" data-index="description" align="center" />
      <a-table-column title="赛段图片" data-index="imageUrl" align="center" :width="100">
        <template #default="{ record }">
          <image-preview :src="record.imageUrl" :width="50" :height="50"/>
        </template>
      </a-table-column>
      <a-table-column title="赛道路径" data-index="pathData" align="center" />
      <a-table-column title="赛事位置" data-index="saishiweizhi" align="center" />
      <a-table-column title="赛事地址" data-index="saishidizhi" align="center" />
      <a-table-column title="状态" data-index="status" align="center">
        <template #default="{ record }">
          <dict-tag :options="race_status" :value="record.status"/>
        </template>
      </a-table-column>
      <a-table-column title="操作" align="center" class-name="small-padding fixed-width">
        <template #default="{ record }">
          <a-space>
            <a-button type="link" @click="handleUpdate(record)" v-privilege="['RaceSys:raceInfo:edit']">
              <template #icon><EditOutlined /></template>
              修改
            </a-button>
            <a-button type="link" danger @click="handleDelete(record)" v-privilege="['RaceSys:raceInfo:remove']">
              <template #icon><DeleteOutlined /></template>
              删除
            </a-button>
          </a-space>
        </template>
      </a-table-column>
    </a-table>

    <div class="table-pagination" style="margin-top: 16px; text-align: right" v-show="total > 0">
      <a-pagination
        :total="total"
        :current="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        @change="handlePageChange"
        @showSizeChange="handlePageSizeChange"
        show-size-changer
        :show-total="(total) => `共 ${total} 条`"
      />
    </div>

    <!-- 添加或修改赛段信息对话框 -->
    <a-modal :title="title" v-model:open="open" width="500px" :confirm-loading="submitLoading">
      <a-form ref="raceInfoRef" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="赛段名称" name="sectionName">
          <a-input v-model:value="form.sectionName" placeholder="请输入赛段名称" />
        </a-form-item>
        <a-form-item label="赛事名称" name="saishi">
          <a-input v-model:value="form.saishi" placeholder="请输入赛事名称" />
        </a-form-item>
        <a-form-item label="赛段介绍" name="description">
          <a-textarea v-model:value="form.description" placeholder="请输入内容" />
        </a-form-item>
        <a-form-item label="赛段图片" name="imageUrl">
          <image-upload v-model:value="form.imageUrl"/>
        </a-form-item>
        <a-form-item label="赛道路径" name="pathData">
          <a-input v-model:value="form.pathData" placeholder="请输入赛道路径" />
        </a-form-item>
        <a-form-item label="赛事位置" name="saishiweizhi">
          <a-input
            v-model:value="form.saishiweizhi"
            placeholder="请选择赛事位置"
            readonly
          />
          <a-button type="primary" @click="openMapDialog" style="margin-top: 8px">选取位置</a-button>
        </a-form-item>
        <a-form-item label="赛事地址" name="saishidizhi">
          <a-input v-model:value="form.saishidizhi" placeholder="请输入赛事地址" />
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-select v-model:value="form.status" placeholder="请选择状态">
            <a-select-option
              v-for="dict in race_status"
              :key="dict.value"
              :value="parseInt(dict.value)"
            >
              {{ dict.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button @click="cancel">取 消</a-button>
        <a-button type="primary" @click="submitForm" :loading="submitLoading">确 定</a-button>
      </template>
    </a-modal>

    <!-- 地图选点对话框 -->
    <a-modal title="地图选点" v-model:open="mapDialogVisible" width="70%" :after-close="closeMapDialog">
      <div id="mapContainer" class="map-container"></div>
      <template #footer>
        <a-button @click="closeMapDialog">取消</a-button>
        <a-button type="primary" @click="confirmLocation">确定</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, getCurrentInstance, nextTick, onMounted } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import { listRaceInfo, getRaceInfo, delRaceInfo, addRaceInfo, updateRaceInfo, listAllSaishi } from "/@/api/offroad/RaceSys/raceInfo";
import { 
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  DownloadOutlined
} from '@ant-design/icons-vue';
import { useDictStore } from '/@/store/modules/system/dict.js';

const { proxy } = getCurrentInstance();
const race_status = useDictStore().getDictData('race_status');

const raceInfoList = ref([]);
const open = ref(false);
const mapDialogVisible = ref(false);
const loading = ref(true);
const submitLoading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const selectedRowKeys = ref([]);

const data = reactive({
  form: {
    sectionName: null,
    saishi: null,
    description: null,
    imageUrl: null,
    pathData: null,
    saishiweizhi: null,
    saishidizhi: null,
    status: null,
    sectionid: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    sectionName: null,
    saishi: null,
    description: null,
    imageUrl: null,
    pathData: null,
    saishiweizhi: null,
    saishidizhi: null,
    status: null,
    sectionid: null
  },
  rules: {

  }
});
const { queryParams, form, rules } = toRefs(data);

let map = null;
let marker = null;
let pickedLngLat = null;
let pickedAddress = '';

function openMapDialog() {
  mapDialogVisible.value = true;
  nextTick(() => {
    if (!map) initMap();
  });
}
function closeMapDialog() {
  mapDialogVisible.value = false;
}
async function initMap() {
  await AMapLoader.load({ key: 'b16861868f00acd6d2cb883e30e5b598', version: '2.0', plugins: ['AMap.Geocoder'] });
  map = new AMap.Map('mapContainer', { zoom: 15, center: [116.397428, 39.90923] });
  const geocoder = new AMap.Geocoder();
  map.on('click', async e => {
    const { lng, lat } = e.lnglat;
    pickedLngLat = [lng, lat];
    if (marker) marker.setPosition([lng, lat]);
    else marker = new AMap.Marker({ position: [lng, lat], map });
    const res = await geocoder.getAddress([lng, lat]);
    pickedAddress = res.regeocode.formattedAddress;
  });
}
function confirmLocation() {
  if (pickedLngLat) {
    form.value.saishiweizhi = `${pickedLngLat[1].toFixed(6)},${pickedLngLat[0].toFixed(6)}`;
    form.value.saishidizhi = pickedAddress;
  }
  closeMapDialog();
}
function cancel() {
  open.value = false;
}

function getList() {
  loading.value = true;
  listRaceInfo(queryParams.value).then(response => {
    raceInfoList.value = response.data.list;
    total.value = response.data.total;
    loading.value = false;
  });
}

function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selectedKeys, selectedRows) {
  selectedRowKeys.value = selectedKeys;
  ids.value = selectedRows.map(item => item.sectionName);
  single.value = selectedRows.length !== 1;
  multiple.value = !selectedRows.length;
}

// 分页页码变化
function handlePageChange(page, pageSize) {
  queryParams.value.pageNum = page;
  queryParams.value.pageSize = pageSize;
  getList();
}

// 分页大小变化
function handlePageSizeChange(current, size) {
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = size;
  getList();
}

function handleAdd() {
  proxy.resetForm("raceInfoRef");
  open.value = true;
  title.value = "添加赛段信息";
}

function handleUpdate(row) {
  proxy.resetForm("raceInfoRef");
  const _sectionName = row.sectionName;
  getRaceInfo(_sectionName).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改赛段信息";
  });
}

function submitForm() {
  proxy.$refs["raceInfoRef"].validate().then(() => {
    submitLoading.value = true;
    if (form.value.sectionid != null) {
      updateRaceInfo(form.value).then(() => {
        proxy.$message.success("修改成功");
        open.value = false;
        getList();
      }).finally(() => {
        submitLoading.value = false;
      });
    } else {
      addRaceInfo(form.value).then(() => {
        proxy.$message.success("新增成功");
        open.value = false;
        getList();
      }).finally(() => {
        submitLoading.value = false;
      });
    }
  });
}

// 新增赛事名称选项
const raceOptions = ref([]);

// 获取赛事名称的方法
const getSaishiOptions = async () => {
  try {
    const res = await listAllSaishi();
    // 转换格式：将字符串数组转换为{value, label}格式
    raceOptions.value = res.data.map(item => ({
      value: item,
      label: item
    }));
  } catch (error) {
    console.error('获取赛事名称失败:', error);
  }
};

// 在组件挂载时获取数据
onMounted(() => {
  getSaishiOptions();
  getList();
});

function handleDelete(row) {
  const _sectionNames = row.sectionName || ids.value;
  proxy.$modal.confirm({
    title: '确认删除',
    content: `是否确认删除赛段信息编号为"${_sectionNames}"的数据项？`,
    onOk() {
      return delRaceInfo(_sectionNames).then(() => {
        getList();
        proxy.$message.success("删除成功");
      });
    }
  });
}

function handleExport() {
  proxy.download('RaceSys/raceInfo/export', { ...queryParams.value }, `raceInfo_${new Date().getTime()}.xlsx`);
}
</script>

<style scoped>
.map-container { width: 100%; height: 400px; border: 1px solid #ddd; border-radius: 4px; }
.mb8 { margin-bottom: 8px; }
.small-padding { padding: 4px; }
.fixed-width { width: 120px; }
</style>